﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
//using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;

using WinFormsUI.Docking;
using InterMessage;
using ChaSQLite.SQLiteManage;
using ChaSQLite.Constants;

namespace ChaSQLite.SubForm
{
    public partial class TableListViewer : DockContent, IMessageClient
    {
        private TreeNode tableNode;
        private TreeNode viewNode;
        private TreeNode indexNode;

        private string databaseName;

        public TableListViewer()
        {
            InitializeComponent();
        }

        public void ReceiveMessage(int type, Object message)
        {
            MSG_CONSTANT nType = (MSG_CONSTANT)type;
            switch (nType)
            {
                case MSG_CONSTANT.MSG_DB_OPEN:
                    databaseName = (string)message;
                    int nItem = cbDBSelect.Items.Add(databaseName);
                    cbDBSelect.SelectedIndex = nItem;

                    openDatabase(databaseName);
                    loadTableInfo();

                    BroadCaster.GetInstance.SendMessage(this, 1, databaseName);
                    break;
                case MSG_CONSTANT.MSG_DB_CLOSE:
                    SQLManager.getInstance.GetBase.CloseDatabase();
                    treeTable.Nodes.Clear();
                    BroadCaster.GetInstance.SendMessage(this, 2, null);
                    break;
            }
            
        }

        private void TableListViewer_Load(object sender, EventArgs e)
        {
            BroadCaster.GetInstance.Attach(this);            
        }

        private bool openDatabase(string fileName)
        {
            bool r = false;
            try
            {
                SQLManager.getInstance.GetBase.OpenDatabase(fileName);
                r = true;
            }
            catch (Exception e)
            {
                r = false;
                MessageBox.Show( e.Message, "오류", MessageBoxButtons.OK, MessageBoxIcon.Error );
            }

            return r;
        }

        private void loadTableInfo()
        {
            treeTable.Nodes.Clear();

            TreeNode root = treeTable.Nodes.Add(databaseName);
            tableNode = root.Nodes.Add("Table");
            viewNode = root.Nodes.Add("View");
            indexNode = root.Nodes.Add("Index");

            root.Expand();

            ArrayList list = SQLManager.getInstance.GetBase.GetTableName();
            foreach(string name in list)
            {
                tableNode.Nodes.Add(name);
            }
            tableNode.Expand();

            ArrayList list2 = SQLManager.getInstance.GetBase.GetViewName();
            foreach (string name in list2)
            {
                viewNode.Nodes.Add(name);
            }
            //viewNode.Expand();

            ArrayList list3 = SQLManager.getInstance.GetBase.GetIndexName();
            foreach (string name in list3)
            {
                indexNode.Nodes.Add(name);
            }
            //indexNode.Expand();

            initializeListControl();            
        }

        private void initializeListControl()
        {
            lstTableInfo.Columns.Add("#", 30);
            lstTableInfo.Columns.Add("이름", 200);
            lstTableInfo.Columns.Add("유형", 100);
        }

        private void treeTable_DoubleClick(object sender, EventArgs e)
        {
            TreeNode node = treeTable.SelectedNode;
            if (node.Level != 2)
                return;

            if (node.Parent.Text.Equals("Table") == false)
                return;

            BroadCaster.GetInstance.SendMessage(this, 3, node.Text);
        }

        private void treeTable_Click(object sender, EventArgs e)
        {
            //TreeNode node = treeTable.SelectedNode;
            //if ( node == null || node.Level != 2)
            //    return;

            //if (node.Parent.Text.Equals("Table") == false)
            //    return;

            //string query = "SELECT sql FROM sqlite_master WHERE name = '" + node.Text + "'";
            //DataTable table = SQLManager.getInstance.GetBase.ExecuteQuery(query);

            //if (table.Rows.Count < 1)
            //    return;

            //string sql = table.Rows[0][0].ToString();

            //int nIndex = sql.LastIndexOf( ')' );

            //if ( nIndex >= 0 )
            //    sql = sql.Substring(0, nIndex-1);

            //char[] separator = { '\n' };
            //string [] temp = sql.Split(separator);

            //string columnName;
            //char [] separator2 = { '\t', ' ' };

            //lstTableInfo.Items.Clear();

            //for (int i = 1; i < temp.Length; i++)
            //{
            //    columnName = temp[i].Trim();
            //    string cn = columnName.ToUpper();
            //    if (cn.IndexOf("CONSTRAINT") >= 0 )
            //        continue;
            //    int lIndex = columnName.LastIndexOf(",");
            //    if (lIndex > 0)
            //        columnName = columnName.Substring(0, lIndex);

            //    string [] columnContents = columnName.Split(separator2);

            //    string[] columnValue = new string[3];
            //    int nValue = 1;

            //    columnValue[0] = string.Format("{0}", i);
            //    for (int j = 0; j < columnContents.Length; j++)
            //    {
            //        if (columnContents[j] == null || columnContents[j].Length == 0)
            //            continue;

            //        columnValue[nValue++] = columnContents[j];
            //        if (nValue == 3)
            //            break;
            //    }

            //    ListViewItem newItem = new ListViewItem(columnValue);
            //    if (i % 2 == 1)
            //        newItem.BackColor = Color.FromName("WhiteSmoke");
            //    lstTableInfo.Items.Add(newItem);
            //}
        }

        private void treeTable_AfterSelect(object sender, TreeViewEventArgs e)
        {
            TreeNode node = treeTable.SelectedNode;
            if (node == null || node.Level != 2)
                return;

            if (node.Parent.Text.Equals("Table") == false)
                return;

            string query = "SELECT sql FROM sqlite_master WHERE name = '" + node.Text + "'";
            DataTable table = SQLManager.getInstance.GetBase.ExecuteQuery(query);

            if (table.Rows.Count < 1)
                return;

            string sql = table.Rows[0][0].ToString();

            int nIndex = sql.LastIndexOf(')');

            if (nIndex >= 0)
                sql = sql.Substring(0, nIndex - 1);

            char[] separator = { '\n' };
            string[] temp = sql.Split(separator);

            string columnName;
            char[] separator2 = { '\t', ' ' };

            lstTableInfo.Items.Clear();

            for (int i = 1; i < temp.Length; i++)
            {
                columnName = temp[i].Trim();
                string cn = columnName.ToUpper();
                if (cn.IndexOf("CONSTRAINT") >= 0)
                    continue;

                if (cn.Length < 5)
                    continue;

                int lIndex = columnName.LastIndexOf(",");
                if (lIndex > 0)
                    columnName = columnName.Substring(0, lIndex);

                string[] columnContents = columnName.Split(separator2);

                string[] columnValue = new string[3];
                int nValue = 1;

                columnValue[0] = string.Format("{0}", i);
                for (int j = 0; j < columnContents.Length; j++)
                {
                    if (columnContents[j] == null || columnContents[j].Length == 0)
                        continue;

                    columnValue[nValue++] = columnContents[j];
                    if (nValue == 3)
                        break;
                }

                ListViewItem newItem = new ListViewItem(columnValue);
                if (i % 2 == 1)
                    newItem.BackColor = Color.FromName("WhiteSmoke");
                lstTableInfo.Items.Add(newItem);
            }
        }

        private void treeTable_MouseClick(object sender, MouseEventArgs e)
        {        
        }

        private void treeTable_MouseDown(object sender, MouseEventArgs e)
        {
            switch (e.Button)
            {                
                case MouseButtons.Right:
                    TreeViewHitTestInfo hitInfo = treeTable.HitTest(e.Location);
                    treeTable.SelectedNode = hitInfo.Node;
                    break;
            }
        }


    }
}
